package com.neusoft.bizcore.auth.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {
    private final static Integer SALT_LENGTH = 6;

    /**
     * 将数组转换成16进制字符串
     *
     * @return String
     */
    private static String byteToHexString(byte[] salt) {
        final StringBuffer hexString = new StringBuffer();
        for (final byte element : salt) {
            String hex = Integer.toHexString(element & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static String getSaltStr() {
        final StringBuilder sb = new StringBuilder();
        final Random r = new Random();
        for (int i = 0; i < MD5Util.SALT_LENGTH; i++) {
            sb.append(r.nextInt(10));
        }

        return sb.toString();
    }

    /**
     * 获得md5之后的16进制字符
     *
     * @param passwd 用户输入密码字符
     * @return String md5加密后密码字符
     */
    public static String getEncryptedPwd(String passwd, byte[] salt) {
        //声明摘要对象，并生成
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (final NoSuchAlgorithmException e) {
            throw new IllegalStateException("Could not find MessageDigest with algorithm \"" + "MD5" + "\"", e);
        }
        //计算MD5函数
        md.update(salt);
        try {
            md.update(passwd.getBytes("UTF-8"));
        } catch (final UnsupportedEncodingException e) {
        }
        //计算后获得字节数组,这就是那128位了即16个元素
        final byte[] digest = md.digest();
        return MD5Util.byteToHexString(digest);
    }

}
